package com.rampage.multitimers;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rampage.multitimers.bo.TimerConfig;
import com.rampage.multitimers.view.TimerView;

public class Main extends Activity implements TextToSpeech.OnInitListener{
	
	public static List<TimerConfig> timerConfigs = new ArrayList<TimerConfig>();
	public static int soundID;
	public static float volume;
	public static SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
	public static TextToSpeech mTts;
	public TimerView longClickedView;
	private List<TimerView> timerViews = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
        mTts = new TextToSpeech(this, this);
        
        findViewById(R.id.add_timer).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
		    	Intent intent = new Intent(Main.this, TimerActivity.class);
				startActivity(intent);
			}
		});
        findViewById(R.id.pause_all).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				for (TimerView view : timerViews) {
					view.pause();
				}
			}
		});
        findViewById(R.id.play_all).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				for (TimerView view : timerViews) {
					view.pause();
					view.start();
				}
			}
		});
        
        /*((GridView)findViewById(R.id.timers)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				((TimerView)arg1).toggle();
			}
		});
        ((GridView)findViewById(R.id.timers)).setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				longClickedView = (TimerView)arg1;
				displayTimerActions();
				return false;
			}
		});*/
    }
    
    @Override
    protected void onPause() {
    	super.onPause();
		for (TimerView view : timerViews) {
			view.pause();
		}
    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }

        super.onDestroy();
    }

    public void onInit(int status) {
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS) {
            // Set preferred language to US english.
            // Note that a language may not be available, and the result will indicate this.
            int result = mTts.setLanguage(Locale.FRENCH);
            // Try this someday for some interesting results.
            // int result mTts.setLanguage(Locale.FRANCE);
            if (result == TextToSpeech.LANG_MISSING_DATA) {
               // Language data is missing or the language is not supported.
            	System.err.println("############################");
            	System.err.println("Language missing");
            	System.err.println("############################");
            } else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
                // Language data is missing or the language is not supported.
             	System.err.println("############################");
             	System.err.println("Language not supported");
             	System.err.println("############################");
             } else {
                // Check the documentation for other possible result codes.
                // For example, the language may be available for the locale,
                // but not for the specified country and variant.
                // Greet the user.
            	/*mTts.speak("Volcano eruption",
                        TextToSpeech.QUEUE_ADD,
                        null);
            	mTts.speak("Seek and Destroy",
                        TextToSpeech.QUEUE_ADD,
                        null);
            	mTts.speak("Earthquake",
                        TextToSpeech.QUEUE_ADD,
                        null);
                        */
            }
        } else {
            // Initialization failed.
            System.err.println("Could not initialize TextToSpeech.");
        }
    }
    @Override
    protected void onResume() {
    	super.onResume();
    	soundID = soundPool.load(this, R.raw.vkosonnerie, 1);
    	AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		volume = actualVolume / maxVolume;
		
		Main.timerConfigs = new ArrayList<TimerConfig>();
		String FILENAME = "timer_configs.txt";
		try {
			FileInputStream fis = openFileInput(FILENAME);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			final Pattern p = 
				Pattern.compile("^([^;]*);([^;]*);([^;]*);([^;]*);([^;]*)$");
			String line = br.readLine();
			while(line != null) {
				Matcher m = p.matcher(line);
				if (m.find()) {
					TimerConfig config = new TimerConfig();
					config.name = m.group(1);
					config.seconds = Integer.parseInt(m.group(2));
					config.warningAt = Integer.parseInt(m.group(3));
					config.voiceWarning = Boolean.parseBoolean(m.group(4));
					config.filename = m.group(5);
					Main.timerConfigs.add(config);
				}
				line = br.readLine();
			}
			br.close();
		} catch (Exception e) {
		}
		
		displayTimers();
    }
    
    private void displayTimers() {
    	((ViewGroup)findViewById(R.id.timers)).removeAllViews();
    	timerViews = new ArrayList<TimerView>();
		if (Main.timerConfigs.size() > 3) {
			findViewById(R.id.add_timer).setVisibility(View.INVISIBLE);
		} else {
			findViewById(R.id.add_timer).setVisibility(View.VISIBLE);
			if (Main.timerConfigs.size() == 0) {
				findViewById(R.id.play_all).setVisibility(View.INVISIBLE);
				findViewById(R.id.pause_all).setVisibility(View.INVISIBLE);
			} else {
				findViewById(R.id.play_all).setVisibility(View.VISIBLE);
				findViewById(R.id.pause_all).setVisibility(View.VISIBLE);
			}
		}
        
		if (Main.timerConfigs.size() < 3) {
			for (TimerConfig config : Main.timerConfigs) {
				TimerView view = new TimerView(Main.this, config);
				view.setOnClickListener(onClickListener);
				view.setOnLongClickListener(onLongClickListener);
				timerViews.add(view);
				((LinearLayout)findViewById(R.id.timers)).addView(view);
				LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
				params.weight = 1;
				view.setLayoutParams(params);
			}
		} else {
			LinearLayout layout1 = new LinearLayout(this);
			layout1.setOrientation(LinearLayout.HORIZONTAL);
			layout1.setBackgroundColor(Color.WHITE);
			((LinearLayout)findViewById(R.id.timers)).addView(layout1);
			LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout1.getLayoutParams();
			params.weight = 1;
			
			LinearLayout layout2 = new LinearLayout(this);
			layout2.setOrientation(LinearLayout.HORIZONTAL);
			layout2.setBackgroundColor(Color.WHITE);
			((LinearLayout)findViewById(R.id.timers)).addView(layout2);
			params = (LinearLayout.LayoutParams)layout2.getLayoutParams();
			params.weight = 1;
			
			int i = 0;
			for (TimerConfig config : Main.timerConfigs) {
				TimerView view = new TimerView(Main.this, config);
				view.setOnClickListener(onClickListener);
				view.setOnLongClickListener(onLongClickListener);
				timerViews.add(view);
				if (i < 2) {
					layout1.addView(view);
				} else {
					layout2.addView(view);
				}
				params = (LinearLayout.LayoutParams)view.getLayoutParams();
				params.weight = 1;
				view.setLayoutParams(params);
				i++;
			}
			if (Main.timerConfigs.size() == 3) {
				TimerView view = new TimerView(Main.this, new TimerConfig());
				view.setVisibility(View.INVISIBLE);
				layout2.addView(view);
				params = (LinearLayout.LayoutParams)view.getLayoutParams();
				params.weight = 1;
				view.setLayoutParams(params);
				/*textView = new TextView(this);
				textView.setText("");
				layout2.addView(textView);
				params = (LinearLayout.LayoutParams)textView.getLayoutParams();
				params.weight = 1;
				textView.setLayoutParams(params);*/
			}
		}
    }
    
    private void displayTimerActions() {
		final CharSequence[] items = new CharSequence[] {getResources().getString(R.string.edit), getResources().getString(R.string.remove)};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(items, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					Intent intent = new Intent(Main.this, TimerActivity.class);
					intent.putExtra("timer", longClickedView.getConfig());
					startActivity(intent);
					break;
				case 1:
					longClickedView.pause();
					Main.timerConfigs.remove(longClickedView.getConfig());
					String FILENAME = "timer_configs.txt";
					try {
						FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
						for (TimerConfig config : Main.timerConfigs) {
							String s = config.toFileSummary() + "\n";
							fos.write(s.getBytes());
						}
						fos.close();
						displayTimers();
					} catch (Exception e) {
					}
					
					break;
				default:
					break;
				}
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
    }
    
    private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			((TimerView)v).toggle();
		}
	};
	private OnLongClickListener onLongClickListener = new OnLongClickListener() {
		@Override
		public boolean onLongClick(View v) {
			longClickedView = (TimerView)v;
			displayTimerActions();
			return false;
		}
	};
}